<template>
	<el-dialog v-model="visible" :title="!dataForm.id ? '创建课程' : '修改课程信息'" :close-on-click-modal="false" draggable>
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" :label-width="200">
			<el-form-item label="课程图片" prop="attachmentList">
				<ma-upload-images v-model="dataForm.attachmentList" :limit="1"></ma-upload-images>
			</el-form-item>
			<el-form-item label="课程名称" prop="courseName">
				<el-input v-model="dataForm.courseName" placeholder="课程名称"></el-input>
			</el-form-item>
			<el-form-item label="课程开始时间" prop="startTime">
				<el-date-picker type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="课程开始时间"
					v-model="dataForm.startTime"></el-date-picker>
			</el-form-item>
			<el-form-item label="课程结束时间" prop="endTime">
				<el-date-picker type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="课程结束时间"
					v-model="dataForm.endTime"></el-date-picker>
			</el-form-item>
			<!-- 添加关联班级按钮 -->
			<el-form-item label="关联班级">
				<el-button type="primary" @click="openClassSelectDialog">添加关联班级</el-button>
			</el-form-item>
			<!-- 展示已选班级的表格 -->
			<el-form-item v-if="dataForm.linkedClasses?.length > 0">
	<el-table :data="dataForm.linkedClasses" border style="width: 100%">
		<el-table-column prop="className" label="班级名称" header-align="center" align="center"></el-table-column>
		<el-table-column prop="classCode" label="班级编码" header-align="center" align="center"></el-table-column>
		<el-table-column label="操作" header-align="center" align="center" width="100">
			<template #default="scope">
				<el-button type="danger" link @click="removeLinkedClass(scope.row)">移除</el-button>
			</template>
		</el-table-column>
	</el-table>
</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>

	<!-- 班级选择弹窗 -->
	<el-dialog v-model="classSelectVisible" title="选择班级" width="80%">
		<ClassSelect @select-class="handleSelectClass"></ClassSelect>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import { useSmCourseApi, useSmCourseSubmitApi } from '@/api/sm/course'
import ClassSelect from '@/views/sm/course/ClassSelect.vue' // 引入新的选择班级组件

const emit = defineEmits(['refreshDataList'])

const visible = defineModel<boolean>('visible')
const dataFormRef = ref()
const classSelectVisible = ref(false) // 控制班级选择弹窗的显示

const dataForm = reactive({
	id: '',
	attachment: '',
	attachmentList: [],
	url: '',
	userId: '',
	courseName: '',
	startTime: '',
	endTime: '',
	desciption: '',
	tenantId: '',
	version: '',
	deleted: '',
	creator: '',
	createTime: '',
	updater: '',
	updateTime: '',
	linkedClasses: [] as Array<{ id: number; className: string; classCode: string }>, // 关联班级列表
})

// 打开班级选择弹窗
const openClassSelectDialog = () => {
	classSelectVisible.value = true
}

// 处理选择的班级
const handleSelectClass = (selectedClasses: Array<{ id: number; className: string; classCode: string }>) => {
	// 将选择的班级添加到 dataForm.linkedClasses 中
	selectedClasses.forEach((classItem) => {
		if (!dataForm.linkedClasses.some((item) => item.id === classItem.id)) {
			dataForm.linkedClasses.push(classItem)
		}
	})
	classSelectVisible.value = false // 关闭班级选择弹窗
	console.log('已选班级:', dataForm.linkedClasses) // 打印日志，检查数据是否正确
}

// 移除关联班级
const removeLinkedClass = (classItem: { id: number; className: string; classCode: string }) => {
	dataForm.linkedClasses = dataForm.linkedClasses.filter((item) => item.id !== classItem.id)
}

const init = (id?: number) => {
	if (id) {
		getCourse(id)
	}
}

const getCourse = (id: number) => {
	useSmCourseApi(id).then(res => {
		Object.assign(dataForm, res.data)
	})
}

const dataRules = ref({
	attachmentList: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	courseName: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	startTime: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	endTime: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	desciption: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate(async (valid: boolean) => {
		if (!valid) {
			return false
		}
		dataForm.attachment = dataForm.attachmentList[0]
		console.log("表单对象:", dataForm);
		useSmCourseSubmitApi(dataForm).then(() => {
			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}

defineExpose({
	init
})
</script>